# -*- coding: utf-8 -*-
# kate: space-indent on; tab-width 4; indent-width 4; indent-mode python; backspace-indents; encoding utf-8; line-numbers on; remove-trailing-space on;
#   Copyright 2010 Thomas Olsen <tanghus@gmail.com>
#
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU Library General Public License as
#   published by the Free Software Foundation; either version 2 or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#
#   GNU General Public License for more details
#
#
#   You should have received a copy of the GNU Library General Public
#   License along with this program; if not, write to the
#   Free Software Foundation, Inc.,
#
#   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#
#

from PyQt4.QtCore import QObject # Qt, QVariant, QSize, SIGNAL
from PyKDE4.kdecore import KUrl
from PyKDE4.kio import *
from xml.dom.minidom import parseString
from webservices import webservices


class Locations(QObject):

    def __init__(self):
        QObject.__init__(self)
        #print "Locations:__init__"
        self.locations = {}
        self.jobdata = ""
        key = webservices["lastfm"]["key"]
        self.source = "http://ws.audioscrobbler.com/2.0/?method=geo.getmetros&api_key=%s" % key
        #print self.source

        job = KIO.get(KUrl(self.source), KIO.NoReload, KIO.HideProgressInfo)
        #print "KIO Job: " + str(job)
        job.data.connect(self.job_received)
        #job.mimetype.connect(self.job_mimetype)
        job.result.connect(self.job_done)

    def job_received(self, job, data):
        if data: #len(data) > 0:
            #print "Locations::job_received\n"
            self.jobdata += str(data)

    def job_done(self, job):
        #print("Locations::job_done")
        #print self.jobdata
        dom = parseString(self.jobdata)
        del self.jobdata
        dmetros = dom.getElementsByTagName('metro')
        for dmetro in dmetros:
            self.parse_metro(dmetro)
        #print "RESULT:"
        #for country in self.countries():
            #print country
            #for metro in self.metros(country):
                #print "\t" + metro

    def parse_metro(self, dmetro):
        #print "Locations::parse_metro, dmetro: " + str(dmetro)
        #print "Locations::parse_metro, metro: " + str(metro)
        #print "Locations::parse_metro, metro: " + str(dmetro.childNodes)
        for elem in dmetro.getElementsByTagName("country"):
            country = self.get_text(elem.childNodes)
            #print "Locations::parse_metro, country: " + country
            if not self.locations.has_key(country):
                self.locations[country] = []
        for elem in dmetro.getElementsByTagName("name"):
            metro = self.get_text(elem.childNodes)
            #print "Locations::parse_metro, metro: " + metro
            self.locations[country].append(metro)

    def get_text(self, elem):
        #print "getText"
        #print "elem: " + str(elem)
        rc = []
        if elem:
            for node in elem:
                #print "get_text, Node: %s" % str(node)
                #print "Type: %i" % node.nodeType
                try:
                    if node.nodeType == node.TEXT_NODE or node.nodeType == node.CDATA_SECTION_NODE:
                        rc.append(node.data)
                except AttributeError:
                    return elem
            return ''.join(rc)
        else:
            return ""

    def countries(self):
        countries = self.locations.keys()
        countries.sort()
        return countries

    def metros(self, country):
        metros = self.locations[country]
        metros.sort()
        return metros
